<?php

namespace app\shop\middleware;


use app\Request;
use app\shop\common\consts\Consts;
use app\shop\model\user\UserModel;
use app\shop\service\admin\AdminLogService;
use app\shop\service\user\UserService;


class ApiAuth
{
    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request, \Closure $next)
    {
        try {
            $token = $request->header('Authorization');
            if (empty($token)) {
                throw new \Exception('登录失效，请重新登录', -1);
            }

            $tokenArr = explode('|', $token);
            if (count($tokenArr) != 2) {
                throw new \Exception('登录失效，请重新登录', -1);
            }
            if (!in_array($tokenArr[0], ['PC', 'APP'])) {
                throw new \Exception('登录失效，请重新登录', -1);
            }

            if (isPhoneNumber($tokenArr[1])) {
                $userInfo = UserModel::where('mobile', $tokenArr[1])->find();
            } else {
                if ($tokenArr[0] == 'PC') {
                    $tokenField = 'pc_token';
                    $tokenValidField = 'pc_token_valid_time';
                } else {
                    $tokenField = 'app_token';
                    $tokenValidField = 'app_token_valid_time';
                }
                $userInfo = UserModel::where($tokenField, $token)->find();
                if (empty($userInfo)) {
                    throw new \Exception('登录失效，请重新登录', -1);
                }
                if ($userInfo[$tokenValidField] <= time()) {
                    throw new \Exception('令牌已失效', -1);
                }
                if (!UserService::isInWorkTime($userInfo)) {
                    throw new \Exception('当前不是工作时间', -1);
                }
            }
            $request->withMiddleware(['userId' => $userInfo['user_id']]);
            $request->withMiddleware(['userInfo' => $userInfo]);
//            AdminLogService::createLog($userInfo['user_id'], $userInfo['realname'], $request->domain(true), $request->pathinfo(),
//                $request->param(), $request->method(), $request->ip(), $request->header('user-agent'), $token);
        } catch (\Exception $exception) {
//            AdminLogService::createLog(0, '', $request->domain(true), $request->pathinfo(),
//                $request->param(), $request->method(), $request->ip(), $request->header('user-agent'), $token, $exception->getMessage());
            return json()->data(['code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}
